import React, { useState, useEffect, FC, SyntheticEvent, ChangeEvent, useRef, MutableRefObject } from 'react'
import {
  Space, Row, Col, Input,
  Form, Table, Modal, Card, InputNumber
} from 'antd'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import { Scrollbars } from 'react-custom-scrollbars'
import * as api from '@/api'
import { IData, PagingSize, IResponseCodeType, } from '@/models/common'
import { DownOutlinedIcon } from '@/models/icons'
import util from '@/utils/util'
import './frmshortcutadmin.scss'
import { IFrmShortcutModel } from '@/models/document'
interface ColumnsDataType {
  [name: string]: string
}
export interface IViewModel {
  shortcutUpdateModalOpen: boolean
  /**
   * 当前修改行信息
   */
  shortcutUpdateRow: ColumnsDataType
  pageLoading: boolean
  /**
   * 表格数据
   */
  shortcutTableList: ColumnsDataType[]
  /**
  * 当前页码
  */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean
  notAuth: boolean
}

const Index: FC = () => {
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      shortcutUpdateModalOpen: false,
      shortcutUpdateRow: {
        id: "",
        name: "",
      },
      pageLoading: false,
      shortcutTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])

  const events = {
    //新增
    onClickAddRow() {
      const { ViewModel } = data
      ViewModel.shortcutUpdateRow.name = ''
      ViewModel.shortcutUpdateRow.id = ''
      ViewModel.shortcutUpdateModalOpen = true
      setData({ ...data })
    },
    //编辑
    onClickEditRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.shortcutUpdateRow.name = record.shortcut_name
      ViewModel.shortcutUpdateRow.id = record.id
      ViewModel.shortcutUpdateModalOpen = true
      setData({ ...data })
    },
    //删除
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该快捷方式吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteShortcut(record.id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateShortcutNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.shortcutUpdateRow.name = e.target.value
      setData({ ...data })
    },
    onShortcutUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.shortcutUpdateRow.name) {
        util.alertTip('请输入快捷方式名称')
        return
      }
      if (ViewModel.shortcutUpdateRow.id) {
        methods.requestUpdateShortcut()
      } else {
        
      }
    },
    onshortcutUpdateRowCancel() {
      const { ViewModel } = data
      ViewModel.shortcutUpdateRow.name = ''
      ViewModel.shortcutUpdateRow.id = ''
      ViewModel.shortcutUpdateModalOpen = false
      setData({ ...data })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        // ViewModel.page = ViewModel.page + 1
        // ViewModel.pageLoading = true
        // setData({ ...data })
        // methods.querySubTableList()
      }
    },
  }
  const methods = {
    /**
     * 加载快捷方式
     */
    async requestShortcutList() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getFrmShortcutList<IFrmShortcutModel>(null)
      const { code, data: ShortcutAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { shortcut_list = [] } = ShortcutAdminData
        ViewModel.shortcutTableList = [...shortcut_list] as ColumnsDataType[]
        if (shortcut_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = false
        }
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 更新
     */
    async requestUpdateShortcut() {
     
    },
    /**
     * 删除
     * @param id 
     */
    async requestDeleteShortcut(id: string) {
    
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '名称',
          align: "left",
          key: 'shortcut_name',
          dataIndex: 'shortcut_name',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickEditRow(_, record, index)}>
                修改
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
                删除
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Card title="快捷方式管理">
          <Col className='frmshortcut-admin-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={6}>
                  <XlButtonFC type='primary' onClick={events.onClickAddRow} style={{visibility:"hidden"}}>新增</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.shortcutTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Row className='tableWrap'>
              <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                <Table
                  scroll={{
                    x: '100%',
                    y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                  }}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  rowKey='id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.shortcutTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Row>
          </Col>
        </Card>
        {/* 添加修改弹出框 */}
        <XlModalFC
          open={data.ViewModel.shortcutUpdateModalOpen}
          onOk={events.onShortcutUpdateRowOk}
          onCancel={events.onshortcutUpdateRowCancel}
          title='修改'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
            autoComplete="off"
          >
            <Form.Item
              label="名称"
              required
            >
              <Input value={data.ViewModel.shortcutUpdateRow.name} onChange={events.onUpdateShortcutNameChange} allowClear placeholder='请输入快捷方式名称' />
            </Form.Item>
          </Form>
        </XlModalFC>
      </>
    }
  }
  return methods.renderPage()
}
export default Index
